package com.atguigu.edu.service.impl;

import com.atguigu.edu.entity.EduSection;
import com.atguigu.edu.mapper.EduSectionMapper;
import com.atguigu.edu.service.EduSectionService;
import com.atguigu.edu.service.VideoServiceFeign;
import com.atguigu.exception.EduException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程小节 服务实现类
 * </p>
 *
 * @author HB
 * @since 2020-11-10
 */
@Service
public class EduSectionServiceImpl extends ServiceImpl<EduSectionMapper, EduSection> implements EduSectionService {
    @Autowired
    private VideoServiceFeign videoServiceFeign;
    @Override
    public void addSection(EduSection section) {
        //1.判断是否存在小节
        QueryWrapper<EduSection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",section.getCourseId());
        queryWrapper.eq("chapter_id",section.getChapterId());
        queryWrapper.eq("title",section.getTitle());
        EduSection existSection = baseMapper.selectOne(queryWrapper);
        if(existSection==null){
            baseMapper.insert(section);
        }else{
            throw new EduException(20001,"存在重复的小节");
        }
    }

    /**
     * 根据小节的id删除小结信息
     * @param id
     */
    @Override
    public void deleteSection(String id) {
        //TODO 删除视频
        //先根据要删除的小结的id，找到所有的小结信息 ，再获取到要删除的小结的视频的视频id
        EduSection eduSection = baseMapper.selectById(id);
        //获取到要删除的小结的视频的视频id
        String videoSourceId = eduSection.getVideoSourceId();
        if(StringUtils.isNotEmpty(videoSourceId)){
            //通过RPC远程删除视频
            videoServiceFeign.deleteSingleVideo(videoSourceId);
        }
        baseMapper.deleteById(id);
    }

    /**
     * 根据课程id删除小结
     * @param courseId
     */
    @Override
    public void deleteSectioByCourseId(String courseId) {
        QueryWrapper<EduSection> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        // TODO 为啥不直接在section表中按照course_id删除就好?
        //因为获取到每个需要删除的小结之后还需要处理删除视频的业务
        //baseMapper.delete(wrapper);
        List<EduSection> eduSectionList = baseMapper.selectList(wrapper);

        //迭代所有小节 把所有视频id封装成一个list集合
        List<String> videoIdList = new ArrayList<>();
        for (EduSection eduSection : eduSectionList) {
            //获取到需要删除的每个小结的视频id
            String videoSourceId = eduSection.getVideoSourceId();
            videoIdList.add(videoSourceId);
        }
       //TODO: 2020/11/12 远程调用video微服务的批量删除方法 删除服务器中的视频
        //已完成 远程rpc调用删除 就可以删除阿里云服务器里面的视频 如果没有远程调用的话 只实现的是删除数据库里面的视频id
        videoServiceFeign.deleteMultiVideo(videoIdList);

        //最后再删除小结信息
        baseMapper.delete(wrapper);


    }
}
